package com.cy.kotlin2test

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import com.cy.kotlin2test.ui.theme.Kotlin2TestTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Kotlin2TestTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
//        FlowDemo().testCodeFlow()
//        FlowDemo().testHotFlow()

//        lifecycleScope.launch {
//            //在主线程，死循环，无事件会挂起协程，不会阻塞主线程
//            FlowDemo().stateFlow.collect{
//                println("stateFlow collect $it")
//            }
//            //stateFlow.collect内部死循环，所以协程内后续代码无法执行
//            println("stateFlow collect")
//        }
//
//        val scope = CoroutineScope(Dispatchers.Default)

        exeOrder()
    }

    /**
     * 协程实质上是通过post runnable执行的，协程执行完自动切线程也是相当于再往对应线程 post 一个 Runnable
     * 输出：
     * exeOrder begin Thread[DefaultDispatcher-worker-1,5,main]
     * exeOrder Dispatchers.IO Thread[DefaultDispatcher-worker-1,5,main]
     * exeOrder end result:5  Thread[DefaultDispatcher-worker-3,5,main]
     */
    fun exeOrder() {
        lifecycleScope.launch(Dispatchers.Default) {
            println("exeOrder begin ${Thread.currentThread()}")
            //可以用变量接withContext？协程内切了协程也是按顺序执行？
            val result = withContext(Dispatchers.IO) {
                delay(1000)
                println("exeOrder Dispatchers.IO ${Thread.currentThread()}")
                5
            }
            //会等待上面的子协程执行完了才执行，子协程执行完了后会自动把线程切换成父协程种类的线程，不一定是同一个线程
            println("exeOrder end result:$result  ${Thread.currentThread()}")
        }

    }
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    Kotlin2TestTheme {
        Greeting("Android")
    }
}